package com.yiboshi.rehrs.util;

/**
 * @author jack 2021/8/13
 */

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

//Nullable需要引入spring-web包

/**
 * jack处理json相关的工具类
 *
 * @create: 2018-04-24 17:20
 **/
public class JacksonUtils {
    public static final ObjectMapper mapper = getObjectMapper();
    //需要引入spring-boot-starter-logging包
    private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class);


    public static ObjectMapper getObjectMapper() {

        ObjectMapper om = new ObjectMapper();
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        //日期序列化
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DateUtils.SQL_TIME)));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DateUtils.SQL_DATE)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DateUtils.TIME)));

        //日期反序列化
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DateUtils.SQL_TIME)));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DateUtils.SQL_DATE)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DateUtils.TIME)));


        om.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        om.registerModule(javaTimeModule);
        om.registerModule(simpleModule);
        om.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
                                                              @Override
                                                              public void serialize(Object value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                                                                  String fieldName = gen.getOutputContext().getCurrentName();
                                                                  try {
                                                                      //反射获取字段类型
                                                                      Field field = gen.getCurrentValue().getClass().getDeclaredField(fieldName);
                                                                      if (Objects.equals(field.getType(), String.class)) {
                                                                          //字符串型空值""
                                                                          gen.writeString("");
                                                                          return;
                                                                      } else if (Objects.equals(field.getType(), Collection.class)) {
                                                                          //列表型空值返回[]
                                                                          gen.writeStartArray();
                                                                          gen.writeEndArray();
                                                                          return;
                                                                      } else if (Objects.equals(field.getType(), List.class)) {
                                                                          //列表型空值返回[]
                                                                          gen.writeStartArray();
                                                                          gen.writeEndArray();
                                                                          return;
                                                                      } else if (Objects.equals(field.getType(), Set.class)) {
                                                                          //列表型空值返回[]
                                                                          gen.writeStartArray();
                                                                          gen.writeEndArray();
                                                                          return;
                                                                      } else if (Objects.equals(field.getType(), Map.class)) {
                                                                          //map型空值返回{}
                                                                          gen.writeStartObject();
                                                                          gen.writeEndObject();
                                                                          return;
                                                                      }
                                                                  } catch (NoSuchFieldException e) {

                                                                  }
                                                                  //默认返回""
                                                                  gen.writeString("");

                                                              }
                                                          }
        );
        return om;
    }

    /**
     * 对象转换为json字符串
     *
     * @param obj
     * @return
     */
    @Nullable
    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj.getClass() == String.class) {
            return (String) obj;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json序列化出错：" + obj, e);
            return null;
        }
    }

    @Nullable
    public static <T> T toBean(String json, Class<T> tClass) {
        try {
            return mapper.readValue(json, tClass);
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    @Nullable
    public static <E> List<E> toList(String json, Class<E> eClass) {
        try {
            if(StrUtil.isEmpty(json)){
                return null;
            }
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    @Nullable
    public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    @Nullable
    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    @Nullable
    public static JSONObject nativeRead(String json) {
        try {
            return mapper.readValue(json, new TypeReference<JSONObject>() {
            });
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }
    @Nullable
    public static JSONArray nativeReadArray(String json) {
        try {
            return mapper.readValue(json, new TypeReference<JSONArray>() {
            });
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class User {
        private String name;
        private Integer age;
    }

    public static void main(String[] args) {
        String json = "{\"namge\":\"zhuxinjun\",\"age\":\"21\"}";
        Map<String, String> map = toMap(json, String.class, String.class);
        System.out.println("map:" + map);
        String j = "[{\"namge\":\"zhuxinjun\",\"age\":\"21\"},{\"namge\":\"yangyang\",\"age\":\"32\"}]";
        JSONArray maps = nativeRead(j, new TypeReference<JSONArray>() {
        });
        JSONObject json1 = nativeRead(json, new TypeReference<JSONObject>() {
        });
        System.out.println(json1);
    }
}
